package com.guo.mixframe.framework.utils

import com.guo.mixframe.framework.configs.CoreConfig
import com.guo.mixframe.framework.configs.ServerConfig
import com.guo.mixframe.framework.exception.CoreException
import com.guo.mixframe.framework.receivers.rpc.RpcClient
import io.protostuff.Tag
import java.util.concurrent.ConcurrentHashMap

/**
 * 游戏服信息帮助类
 */
class CrossServerHelper {
    data class GetIPOfZoneReq(@Tag(1) val zone: String)

    data class GetIPOfZoneResp(@Tag(1) val ip: String, @Tag(2) val redisIp: String)



    companion object {

        fun playerIdWithZone(zone: String, playerId: String): String {
            return "${zone}_$playerId"
        }

        fun calcPlayerId(idWithZone: String): List<String>{
            return idWithZone.split('_').toList()
        }

        private val ipMap: MutableMap<String, GetIPOfZoneResp?> = ConcurrentHashMap()

        /**
         * 获取zone对应的分区信息，包含局域网ip和redisIp
         */
        private suspend fun getLogicServerConfigOfZone(zone: String): GetIPOfZoneResp {
            return if (ipMap.containsKey(zone)) {
                ipMap[zone]
            } else {
                if (CoreConfig.getInstance().isLogin){
                    val server = ServerConfig.getInstance().getGameServerByNameId(zone)
                    val resp = GetIPOfZoneResp(server.localIP, server.redisIp)
                    ipMap.putIfAbsent(zone, resp)
                    resp
                } else {
                    val req = GetIPOfZoneReq(zone)
                    val resp = RpcClient.rpcToHost("getIPOfZone", req, GetIPOfZoneResp::class.java, "")
                    ipMap.putIfAbsent(zone, resp)
                    resp
                }
            } ?: throw CoreException().throwException(CoreException.ZoneNotExist)
        }

        /**
         * 清楚缓存
         */
        fun clearCache() {
            ipMap.clear();
        }

        /**
         * 获取zone对应局域网ip
         */
        suspend fun getIPOfZone(zone: String): String {
            return getLogicServerConfigOfZone(zone).ip
        }

        /**
         * 获取zone对应redisIp
         */
        suspend fun getRedisIPOfZone(zone: String): String {
            return getLogicServerConfigOfZone(zone).redisIp
        }
    }
}
